﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Docsbox.Layouts.Docsbox
{
    public partial class associateProject : LayoutsPageBase
    {
        private static string _listId;
        private static string _itemId;
        private List<int> selectedProjectIds;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack){
                _listId = Request.QueryString["List"];
                _itemId = Request.QueryString["ID"];
                LoadProjectsList(string.Empty);
            }else
            {
                selectedProjectIds = new List<int>();
                for(int i=0;i< listGV.Rows.Count; i++)
                {
                    int projectId = Convert.ToInt32(listGV.DataKeys[i][0]);
                    CheckBox cb = (CheckBox) listGV.Rows[i].FindControl("checkBoxSelected");
                    if(cb.Checked)
                    {
                        selectedProjectIds.Add(projectId);
                    }
                }

                if(selectedProjectIds.Count > 1)
                {

                    Context.Response.Write("<script type='text/javascript'>alert('Select a single project from the list.');</script>");
                    return;
                }

                string office = ddlOffices.SelectedItem.Text;
                string status = ddlStatus.SelectedItem.Text;
                string keyword = txtKeyword.Text.Trim();
                string queryStr = BuildQueryString(office, status, keyword);
                LoadProjectsList(queryStr);

            }
                LoadSearchFilters();
        }

        private void LoadSearchFilters()
        {
            SPSite siteCollection = this.Site;
            SPWeb web = this.Web;

            SPList financeOffices = web.Lists["FinanceBranches"];

            foreach (SPListItem item in financeOffices.Items)
            {
                ddlOffices.Items.Add(new ListItem(item["Title"].ToString(),item.ID.ToString()));
            }


            List<string> statuses = new List<string>();

            SPList statusList = web.Lists["ProjectStatus"];

            foreach (SPListItem item in statusList.Items)
            {
                ddlStatus.Items.Add(new ListItem(item["Title"].ToString(), item.ID.ToString()));
            }
        }

        //load the project list fields
        private void LoadProjectsList(string queryString)
        {
            SPSite siteCollection = this.Site;
            SPWeb site = this.Web;

            SPList list = site.Lists["Projects"];

            SPQuery query = new SPQuery(list.DefaultView);
            SPListItemCollection result;
            if(String.IsNullOrEmpty(queryString))
            {
                result = list.GetItems(list.DefaultView);
            }else
            {
                query.Query = queryString;
                result = list.GetItems(query);
            }
            DataTable database = new DataTable();
            database.Columns.Add("ItemId");
            database.Columns.Add("MTFNumber");
            database.Columns.Add("FirstName");
            database.Columns.Add("Surname");
            database.Columns.Add("RegistrationNumber");
            database.Columns.Add("Office");
            database.Columns.Add("Status");

            foreach (SPListItem item in result)
            {
                DataRow row = database.NewRow();
                row["ItemId"] = item.ID;
                row["MTFNumber"] = ConvertFieldToString(item["Title"], FieldType.Text);
                row["FirstName"] = ConvertFieldToString(item["FirstName"], FieldType.Text);
                row["Surname"] = ConvertFieldToString(item["Surname"], FieldType.Text);
                row["RegistrationNumber"] = ConvertFieldToString(item["RegistrationNumber"], FieldType.Text);
                row["Office"] = ConvertFieldToString(item["FinanceOffice"], FieldType.Lookup);
                row["Status"] = ConvertFieldToString(item["ProjectStatus"], FieldType.Lookup);
                database.Rows.Add(row);
            }

            listGV.DataSource = database;
            listGV.DataBind();



            //projectsLVBQ.List = list;
            //SPQuery query = new SPQuery(list.DefaultView);
            //if (queryString.Length != 0)
            //    query.Query = queryString;
            //projectsLVBQ.Query = query;
        }

        private string ConvertFieldToString(object fieldValue, FieldType type)
        {
            if (fieldValue == null)
                return string.Empty;
            if (type == FieldType.Text)
                return fieldValue.ToString();
            if (type == FieldType.Note)
                return fieldValue.ToString();
            if (type == FieldType.DateTime)
                return fieldValue.ToString();
            if (type == FieldType.Lookup)
                return ConvertLookupFieldToString(fieldValue);
            return string.Empty;
        }

        private string ConvertLookupFieldToString(object lookupData)
        {
            string lookup = lookupData.ToString();
            string splitter = ";#";
            int index = lookup.LastIndexOf(splitter, StringComparison.CurrentCultureIgnoreCase);
            return lookup.Substring(index + 1);
        }

        private string BuildQueryString(string office, string status, string keyword)
        {
            if (string.IsNullOrEmpty(keyword))
            {
                string query = @"
                                <Where>
		                            <And>
			                            <Eq>
				                            <FieldRef Name='FinanceOffice' />
				                            <Value Type='Lookup'>{0}</Value>
			                            </Eq>
			                            <Eq>
				                            <FieldRef Name='ProjectStatus' />
				                            <Value Type='Lookup'>{1}</Value>
			                            </Eq>
		                            </And>
                                </Where>";
                return string.Format(query, office, status);
            }
            else
            {
                string query = @"
                            <Where>
	                            <And>
		                            <And>
			                            <Eq>
				                            <FieldRef Name='FinanceOffice' />
				                            <Value Type='Lookup'>{0}</Value>
			                            </Eq>
			                            <Eq>
				                            <FieldRef Name='ProjectStatus' />
				                            <Value Type='Lookup'>{1}</Value>
			                            </Eq>
		                            </And>
		                            <Or>
			                            <Or>
				                            <Or>
					                            <Or>
						                            <Contains>
							                            <FieldRef Name='Title'/>
							                            <Value Type='Text'>{2}</Value>
						                            </Contains>
						                            <Contains>
							                            <FieldRef Name='RegistrationNumber'/>
							                            <Value Type='Text'>{2}</Value>
						                            </Contains>
					                            </Or>
					                            <Contains>
						                            <FieldRef Name='Surname'/>
						                            <Value Type='Text'>{2}</Value>
					                            </Contains>
				                            </Or>
				                            <Contains>
					                            <FieldRef Name='ProjectComment' />
					                            <Value Type='Note'>{2}</Value>
				                            </Contains>
			                            </Or>
			                            <Contains>
				                            <FieldRef Name='FirstName' />
				                            <Value Type='Text'>{2}</Value>
			                            </Contains>
		                            </Or>
	                            </And>
                            </Where>";
                return string.Format(query, office, status, keyword);
            }
        }

        private void AssociateDocumentToProject(int projectId)
        {
            SPSite siteCollection = this.Site;
            SPWeb site = this.Web;

            Guid listId = new Guid(_listId);
            int itemId = Convert.ToInt32(_itemId);

            site.AllowUnsafeUpdates = true;
            SPList documents = site.Lists[listId];
            SPListItem document = documents.Items.GetItemById(itemId);
            document["Project"] = projectId;
            document.Update();
            site.AllowUnsafeUpdates = false;
        }
        

        public void btnSearch_Cilck(Object sender, EventArgs e)
        {

        }

        public void btnSelect_Click(object sender, EventArgs e)
        {


            if (selectedProjectIds.Count == 0)
            {
                Context.Response.Write("<script type='text/javascript'>alert('Select a  project from the list first.');</script>");
                return;
            }
            int projectId = selectedProjectIds[0];
            AssociateDocumentToProject(projectId);

            ClosePopUp();
        }


        private void ClosePopUp()
        {
            Context.Response.Write("<Script type='text/javascript'>window.frameElement.commitPopup();</script>");
            Context.Response.Flush();
            Context.Response.End();
        }
    }
    public enum FieldType
    {
        Text,
        Note,
        DateTime,
        Lookup
    }
}
